package controller;

import exception.ActNoNotExistException;
import exception.MoneyNotEnoughException;
import exception.TransferException;
import pojo.Account;
import service.AccountService;
import service.AccountServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

@WebServlet("/transfer")
public class AccountController extends HttpServlet {

    private AccountService accountService = new AccountServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fromActNo = request.getParameter("fromActNo");
        String toActNo = request.getParameter("toActNo");
        BigDecimal money = new BigDecimal(request.getParameter("money"));
        try {
            accountService.transfer(fromActNo,toActNo,money);
            response.sendRedirect(request.getContextPath()+"/success.html");
        } catch (MoneyNotEnoughException | ActNoNotExistException | TransferException e) {
            request.setAttribute("errInfo",e.getMessage());
            RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp");
            dispatcher.forward(request,response);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
